package CrowdCountingMVC.CCModel.Task.TextTask;

import CrowdCounting.Model.Util;
import CrowdCountingMVC.CCModel.CrowdCountingModel;
import CrowdCountingMVC.CCModel.Task.PythonScriptTask.PythonRunTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static Const.State.*;

public class LoadTextAndNotifyTask implements Runnable {

    CrowdCountingModel crowdCountingModel;
    PythonRunTask pythonRunTask;
    BufferedReader pythonProcessTextReader;

    public LoadTextAndNotifyTask(CrowdCountingModel crowdCountingModel, PythonRunTask pythonRunTask) {
        this.crowdCountingModel = crowdCountingModel;
        this.pythonRunTask = pythonRunTask;
    }

    @Override
    public void run() {
        loadTextAndNotify();
    }

    private void loadTextAndNotify() {
        while (crowdCountingModel.getShowState() != START) ;
        try {
            pythonProcessTextReader = new BufferedReader(new InputStreamReader(pythonRunTask.getProcess().getInputStream(), "gbk"));
            String line;
            while ((line = pythonProcessTextReader.readLine()) != null) {
                System.out.println(line);
                crowdCountingModel.setPersonNumText(line);
                crowdCountingModel.notifyPersonNumShowObserver();
                while (crowdCountingModel.getShowState() == STOP) {
                    System.out.println("暂停中");
                    Util.sleepTime(1000);
                }

                if (crowdCountingModel.getShowState() == CLOSE) {
                    System.out.println("已关闭");
                }
            }
            pythonProcessTextReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
